package com.hmall.geteway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.geteway.config.AuthProperties;
import com.hmall.geteway.config.JwtProperties;
import com.hmall.geteway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher=new AntPathMatcher();
    private final JwtTool jwtTool;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.判断是否要进行登录的请求
        ServerHttpRequest request = exchange.getRequest();
        if (isExclude(request.getPath().toString())){
            return chain.filter(exchange);
        }
        //如果不是需要登录的地址则放行，比如：登录，搜索商品
        String token = request.getHeaders().getFirst("authorization");
        try {
            Long userId = jwtTool.parseToken(token);
            System.out.println("userId:"+userId);
            exchange.mutate().request(builder -> {
                builder.header("user-info", userId.toString());
            });
        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        return chain.filter(exchange);
    }

    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath, path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
